<?php
/**
 * @author Lukas Normantas
 */
class Blog_CommentGateway
{
    /**
     * @var Zend_Form
     */
    protected $_form = null;

    public function getForm($post_id, $comment_id = null){
        if ($this->_form == null){
            $this->_form = new Blog_CommentForm();
        }

        $this->_form->getElement('post_id')->setValue($post_id);

        if ($comment_id) {
            $blogComment = Doctrine::getTable('Blog_Comment')->find($comment_id);
            $this->_form->setDefaults($blogComment->toArray());
        }
        return $this->_form;
    }

    public function add($data, $post_id)
    {
        $form = $this->getForm($post_id);
        //$form->getElement('post_id')->setValue($post_id);
        if ($form->isValid( $data )){
            $blogComment = new Blog_Comment();
            $blogComment->fromArray($form->getValues());
            $blogComment->author_id = Zend_Auth::getInstance()->getIdentity()->getUserId();
            $blogComment->save();
            return true;
        }
        return false;
    }

    public function getPager($post_id, $currentPage)
    {
        $resultsPerPage = 20;

        return new Doctrine_Pager(
            Doctrine_Query::create()
                ->select('c.*, p.*')
                ->from( 'Blog_Comment c' )
                ->leftJoin( 'c.post p' )
                ->leftJoin( 'c.author u' )
                ->where('p.id = ?', $post_id )
                ->orderBy('c.created_at DESC' ),
                $currentPage,
                $resultsPerPage
        );       
    }

    public function save($data, $form)
    {
        if ($form->isValid( $data )){
            $comment = new Blog_Comment();
            $comment ->fromArray($form->getValues());
            $comment ->author_id = Zend_Auth::getInstance()->getIdentity()->getUserId();
            $comment ->save();
            return true;
        }
        return false;
    }




    public function getAdminPager($currentPage)
    {
        $resultsPerPage = 4;

        return new Doctrine_Pager(
            Doctrine_Query::create()
                ->from( 'Blog_Post p' )
                ->leftJoin( 'p.Author u' )
                ->orderBy( 'p.title ASC' ),
                $currentPage,
                $resultsPerPage
        );
    }

    public function deletePosts($ids)
    {
        $q = Doctrine_Query::create()
            ->delete('Blog_Post p')
            ->where('p.id IN ?', array($ids));
        return $q->execute();
    }
}

